package com.kenyi.co.ui.video;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.util.Util;
import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnNetWorkErrorListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.kenyi.co.R;
import com.kenyi.co.common.ui.BaseActivity;
import com.kenyi.co.common.utils.RouteUtils;
import com.kenyi.co.okhttp.OkHttpUtils;
import com.kenyi.co.okhttp.callback.StringCallback;
import com.kenyi.co.okhttp.utils.GsonResultok;
import com.kenyi.co.ui.login.RegisterActivity;
import com.kenyi.co.ui.video.adapter.VideoDetailAdapter;
import com.kenyi.co.utils.CommonUtils;
import com.kenyi.co.utils.GlideImageLoader;
import com.kenyi.co.utils.GlideRoundedCorners;
import com.kenyi.co.utils.LogU;
import com.kenyi.co.utils.NetConfig;
import com.kenyi.co.utils.SharepUtils;
import com.stay4it.banner.Banner;
import com.stay4it.banner.BannerConfig;
import com.stay4it.banner.Transformer;
import com.stay4it.banner.listener.OnBannerListener;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

import static com.kenyi.co.MyApplication.getContext;
import static com.kenyi.co.utils.CommonUtils.isFastClick;


/**
 * 文章详情页
 */
public class VideoDetailContentActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "SettingActivity";
    private TextView tv_home_title;
    private TextView tv_video_sc;
    private TextView tv_video_num, tv_vedio_title, tv_look;
    private TextView tv_video_ad_title, tv_video_ad_title2, tv_video_header_2, tv_video_header_1;
    private Toolbar toolbar;
    private ViewGroup mViewParent;
    private LinearLayout li_video_sc;
    private FrameLayout web_home_video_1;
    private String id;
    private WebView mWebView;
    private ImageView iv_video_sc;
    private RelativeLayout li_home_vier;
    private RelativeLayout li_home_vier2;
    private LRecyclerViewAdapter mLRecyclerViewAdapter = null;
    private LRecyclerView mRecyclerView = null;
    private Banner lunbo;
    private Banner footerlunbo;
    private Boolean AutoPlay = false;
    private Boolean is_sc = false;
    ;
    private VideoDetailAdapter mDataAdapter = null;
    private LinearLayout footeradView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_detail_content);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();

        if (bundle != null && bundle.containsKey("id")) {
            id = bundle.getString("id");
        }
        initView();
        mRecyclerView = (LRecyclerView) findViewById(R.id.list);

        mDataAdapter = new VideoDetailAdapter(this);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDataAdapter);
        mRecyclerView.setAdapter(mLRecyclerViewAdapter);
        DividerDecoration divider = new DividerDecoration.Builder(this)
                .setHeight(R.dimen.common_30dp)
                .setPadding(R.dimen.default_divider_padding_10)
                .setColorResource(R.color.white)
                .build();
        mRecyclerView.addItemDecoration(divider);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader);
        mRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerView.setPullRefreshEnabled(false);
        LinearLayout adView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.video_detail_content_header, null);
        tv_vedio_title = adView.findViewById(R.id.tv_vedio_title);
        web_home_video_1 = adView.findViewById(R.id.web_home_video_1);
        tv_video_sc = adView.findViewById(R.id.tv_video_sc);
        tv_video_num = adView.findViewById(R.id.tv_video_num);
        tv_look = adView.findViewById(R.id.tv_look);
        li_video_sc = adView.findViewById(R.id.li_video_sc);
        iv_video_sc = adView.findViewById(R.id.iv_video_sc);
        tv_video_ad_title = adView.findViewById(R.id.tv_video_ad_title);
        lunbo = (Banner) adView.findViewById(R.id.banner);
        tv_video_header_1 = adView.findViewById(R.id.tv_video_header_1);
        li_home_vier = (RelativeLayout) adView.findViewById(R.id.li_home_vier);
        ViewGroup.LayoutParams vParams = li_home_vier.getLayoutParams();
        float density = getResources().getDisplayMetrics().density;//dp转px
        int biankaung = (int) (32 * density + 0.5);
        vParams.height = (int) ((CommonUtils.getMobileWidth(this) - biankaung) * 0.47);
        vParams.width = (int) (CommonUtils.getMobileWidth(this) - biankaung);
        li_home_vier.setLayoutParams(vParams);
        footeradView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.video_detail_footer, null);
        tv_video_header_2 = footeradView.findViewById(R.id.tv_video_header_1);
        footerlunbo = (Banner) footeradView.findViewById(R.id.banner);
        tv_video_ad_title2 = footeradView.findViewById(R.id.tv_video_ad_title);
        li_home_vier2 = (RelativeLayout) footeradView.findViewById(R.id.li_home_vier);
        ViewGroup.LayoutParams vParams2 = li_home_vier2.getLayoutParams();
        vParams2.height = (int) ((CommonUtils.getMobileWidth(this) - biankaung) * 0.47);
        vParams2.width = (int) (CommonUtils.getMobileWidth(this) - biankaung);
        li_home_vier2.setLayoutParams(vParams2);
        mLRecyclerViewAdapter.addFooterView(footeradView);
        mViewParent = (ViewGroup) adView.findViewById(R.id.web_home_video_1);
        li_video_sc.setOnClickListener(this);
        mLRecyclerViewAdapter.addHeaderView(adView);
        mWebView = new WebView(this);
        mWebView.setFocusable(false);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mRecyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        getVideoDetail();
        //是否禁用自动加载更多功能,false为禁用, 默认开启自动加载更多功能
        mRecyclerView.setLoadMoreEnabled(true);
        mLRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                VideoDetailBean.DatasBean.RecommendBean item = mDataAdapter.getDataList().get(position);
                if ("0".equals(item.getType())) {
                    if (!isFastClick()) {
                        return;
                    }
                    Intent metags = new Intent(VideoDetailContentActivity.this, VideoDetailActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("id", item.getId() + "");
                    bundle.putString("is_again", "1");
                    metags.putExtras(bundle);
                    startActivity(metags);
                } else {
                    Map<String, String> params = new HashMap<>();
                    params.put("title", item.getAds().get(0).getTitle());
                    params.put("articleId", id);
                    params.put("url2", item.getAds().get(0).getUrl2());
                    params.put("advid", item.getAds().get(0).getId());
                    params.put("adPosition", 4 + "");
                    params.put("pageName","VideoDetailContentActivity");
//                            RouteUtils.Route(VideoDetailActivity.this, itemListad.get(i).getUrl(), itemListad.get(i).getTitle());
                    RouteUtils.RoutebyAd(getApplicationContext(), VideoDetailContentActivity.this, item.getAds().get(0).getUrl(), params);
                }

            }
        });

        //设置底部加载文字提示
        mRecyclerView.setFooterViewHint("努力加载中", "已经加载全部", "网络不给力啊，点击再试一次吧");
        mRecyclerView.setOnNetWorkErrorListener(new OnNetWorkErrorListener() {
            @Override
            public void reload() {

            }
        });
        mRecyclerView.refresh();

    }

    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.white));//设置状态栏颜色
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//实现状态栏图标和文字颜色为暗色
        }
    }

    private void initView() {
        setStatusBar();
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_home_title = (TextView) findViewById(R.id.tv_home_title);

        tv_home_title.setText("摄游视界");


    }

    @JavascriptInterface
    public void resize(final float height) {
        ((Activity) getContext()).runOnUiThread(new Runnable() {
            @Override
            public void run() {

                web_home_video_1.setLayoutParams(new LinearLayout.LayoutParams(getResources().getDisplayMetrics().widthPixels, (int) (height * getResources().getDisplayMetrics().density)));
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("设置页面");
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();

        MobclickAgent.onPageEnd("设置页面");
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected void onStart() {
        super.onStart();
        if (AutoPlay) {


            getCollect();
        }
    }

    /**
     * 收藏视频
     */
    public void getCollect() {

        Map<String, String> params = new HashMap<>();

        params.put("userId", "" + SharepUtils.getString_info(this, SharepUtils.USER_LOGIN_USERID));
        params.put("articlesId", "" + id);

        Map<String, String> headers = new HashMap<>();

        headers.put("Content-Type", "application/json");
        headers.put("Authorization", SharepUtils.getString_info(this, SharepUtils.USER_LOGIN_TOKEN));
        String url = NetConfig.APPUSER_COLLECT;
        OkHttpUtils.post()
                .url(url)
                .params(params)
                .headers(headers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();

                        GsonResultok packlist1 = gson.fromJson(response, GsonResultok.class);
                        int code = packlist1.getCode();
                        if (code == 200) {
                            AutoPlay = false;
                            is_sc = true;
                            SharepUtils.setString_info(VideoDetailContentActivity.this,"1", SharepUtils.IS_SC);
                            tv_video_sc.setText("已收藏");
                            iv_video_sc.setImageResource(R.drawable.iv_video_sc_ok);

                        } else if (code == 401) {
                            is_sc = true;
                            SharepUtils.setString_info(VideoDetailContentActivity.this,"1", SharepUtils.IS_SC);
                            tv_video_sc.setText("已收藏");
                            iv_video_sc.setImageResource(R.drawable.iv_video_sc_ok);
                        }


                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.li_video_sc:
                if ("1".equals(SharepUtils.getString_info(VideoDetailContentActivity.this, SharepUtils.USER_IS_LOGIN))) {
                    if (is_sc) {
                        getDeleteCollectActicles(id);
                    } else {
                        getCollect();
                    }


                } else {
                    AutoPlay = true;
                    Intent intentlogin = new Intent(VideoDetailContentActivity.this, RegisterActivity.class);
                    Bundle bundlelogin = new Bundle();
                    bundlelogin.putString("isfinish", "1");
                    intentlogin.putExtras(bundlelogin);

                    startActivity(intentlogin);
                    overridePendingTransition(R.anim.slide_out_to_top, R.anim.slide_out_to_bottom);
                }

                break;


        }
    }

    /**
     * 获取系统头像库
     */
    public void getVideoDetail() {

        Map<String, String> params = new HashMap<>();

        params.put("id", "" + id);

        Map<String, String> headers = new HashMap<>();

        headers.put("Authorization", SharepUtils.getString_info(VideoDetailContentActivity.this, SharepUtils.USER_LOGIN_TOKEN));


        String url = NetConfig.VIDEO_DETAIL;

        OkHttpUtils.get()
                .url(url)
                .params(params)
                .headers(headers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {



                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();

                        int num = 0;
                        VideoDetailBean packlist = gson.fromJson(response, VideoDetailBean.class);
                        int code = packlist.getCode();
                        if (code == 200) {
                            li_video_sc.setVisibility(View.VISIBLE);
                            tv_vedio_title.setText(packlist.getDatas().getArticle().getShowTitle());
//                            double readnum = packlist.getDatas().getArticle().getReadCount();
//                            readnum = readnum / 1000;
//                            Math.ceil(readnum);

//                            tv_video_num.setText(Math.ceil(readnum) / 10 + "阅读");
                            tv_video_num.setText(packlist.getDatas().getArticle().getReadCount() + "阅读");

//                            mWebView.loadDataWithBaseURL(null, packlist.getDatas().getArticle().getContent(), "text/html", "utf-8", null);
                            String content = packlist.getDatas().getArticle().getContent();
                            content = "<html><head><style>img{width:100% !important;}</style></head><body style='margin:0;padding:0'>" + content + "</body></html>";
//                            content = content.replace("<mip-img popup", "<img style=max-width:100%;\"");
//                            content = content.replace("mip-img", "img");
                            mWebView.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
                            mViewParent.addView(mWebView, new FrameLayout.LayoutParams(
                                    FrameLayout.LayoutParams.MATCH_PARENT,
                                    FrameLayout.LayoutParams.WRAP_CONTENT));

//                            setupWebView();
                            List<VideoDetailBean.DatasBean.RecommendBean> itemList = new ArrayList<VideoDetailBean.DatasBean.RecommendBean>();
                            itemList = packlist.getDatas().getRecommend();
                            if (packlist.getDatas().getArticle().isIsFav()) {
                                iv_video_sc.setImageResource(R.drawable.iv_video_sc_ok);
                                is_sc = true;
                                SharepUtils.setString_info(VideoDetailContentActivity.this,"1", SharepUtils.IS_SC);
                                tv_video_sc.setText("已收藏");
                            } else {
                                SharepUtils.setString_info(VideoDetailContentActivity.this,"0", SharepUtils.IS_SC);
                                iv_video_sc.setImageResource(R.drawable.iv_video_sc);
                                is_sc = false;
                                tv_video_sc.setText("收藏");
                            }

                            if (packlist.getDatas().getAdPosition().getFirstAd().size() > 0) {
                                initBanner(packlist.getDatas().getAdPosition().getFirstAd());
                                tv_video_header_1.setVisibility(View.VISIBLE);
                            } else {
                                li_home_vier.setVisibility(View.GONE);
                                tv_video_ad_title.setVisibility(View.GONE);
                                tv_video_header_1.setVisibility(View.GONE);
                                lunbo.setVisibility(View.GONE);


                            }
                            if (packlist.getDatas().getAdPosition().getArticleBottom().size() > 0) {
                                initBanner2(packlist.getDatas().getAdPosition().getArticleBottom());
                                tv_video_header_2.setVisibility(View.VISIBLE);
                            } else {
                                li_home_vier2.setVisibility(View.GONE);
                                tv_video_ad_title2.setVisibility(View.GONE);
                                footerlunbo.setVisibility(View.GONE);
                                tv_video_header_2.setVisibility(View.GONE);

                            }


                            tv_look.setVisibility(View.VISIBLE);
                            for (int i = 0; i < itemList.size(); i++) {
                                if ("0".equals(itemList.get(i).getType())) {

                                    itemList.get(i).setItemType(1);
                                } else {
                                    if (itemList.get(i).getAds().size() == 1) {
                                        if (itemList.get(i).getAds().get(0).getImgs().size() > 1) {

                                            itemList.get(i).setItemType(2);
                                        } else {
                                            int width = Integer.parseInt(itemList.get(i).getAds().get(0).getWidth());
                                            if (width > 200) {

                                                itemList.get(i).setItemType(4);
                                            } else {

                                                itemList.get(i).setItemType(3);
                                            }

                                        }
                                    } else if (itemList.get(i).getAds().size() > 1) {

                                        itemList.get(i).setItemType(5);
                                    }

                                }
                            }


                            num = itemList.size();
                            mDataAdapter.addAll(itemList);

                            mRecyclerView.setVisibility(View.VISIBLE);
                            mRecyclerView.refreshComplete(num);
//                            mWebView.loadData(packlist.getDatas().getArticle().getContent(), "text/html", "UTF-8");
                        }


                    }
                });
    }

    /**
     * 初始化
     */
    private void initBanner(final List<VideoDetailBean.DatasBean.AdPositionBean.FirstAdBean> list) {
        tv_video_ad_title.setText(list.get(0).getTitle());
        lunbo.setDelayTime(3000)
                .setBannerAnimation(Transformer.DepthPage)
                .setImages(list)
                .setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
                .setIndicatorGravity(BannerConfig.CENTER)
                .setImageLoader(new GlideImageLoader() {
                    @Override
                    public void displayImage(Context context, Object path, ImageView imageView) {
                        VideoDetailBean.DatasBean.AdPositionBean.FirstAdBean bannerInfo = (VideoDetailBean.DatasBean.AdPositionBean.FirstAdBean) path;
                        try {
                            if (Util.isOnMainThread() && context != null) {
                                RequestOptions myOptions = new RequestOptions()
                                        .error(R.drawable.iv_bg_video_right)
                                        .fitCenter()
                                        .optionalTransform
                                                (new GlideRoundedCorners(CommonUtils.dip2px(context, 5)
                                                        , GlideRoundedCorners.CornerType.ALL));
                                Glide.with(context)
                                        .load(bannerInfo.getImgs().get(0))
                                        .apply(myOptions)
                                        .into(imageView);
                            }
                        } catch (Exception e) {
                        }

                    }
                }).start();

        lunbo.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Map<String, String> params = new HashMap<>();


                params.put("title", list.get(position).getTitle());
                params.put("articleId", id);
                params.put("url2", list.get(position).getUrl2());
                params.put("advid", list.get(position).getId());
                params.put("adPosition", "7");
                params.put("pageName","VideoDetailContentActivity");

                params.put("carrierName", CommonUtils.getOperator(VideoDetailContentActivity.this));
                RouteUtils.RoutebyAd(getApplicationContext(), VideoDetailContentActivity.this, list.get(position).getUrl(), params);
//                RouteUtils.Route(VideoDetailContentActivity.this, list.get(position).getUrl(), list.get(position).getTitle());

            }
        });
    }

    /**
     * 初始化
     */
    private void initBanner2(final List<VideoDetailBean.DatasBean.AdPositionBean.ArticleBottomBean> list) {
        tv_video_ad_title2.setText(list.get(0).getTitle());
        footerlunbo.setDelayTime(3000)
                .setBannerAnimation(Transformer.DepthPage)
                .setImages(list)
                .setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
                .setIndicatorGravity(BannerConfig.CENTER)
                .setImageLoader(new GlideImageLoader() {
                    @Override
                    public void displayImage(Context context, Object path, ImageView imageView) {
                        VideoDetailBean.DatasBean.AdPositionBean.ArticleBottomBean bannerInfo = (VideoDetailBean.DatasBean.AdPositionBean.ArticleBottomBean) path;
                        if (Util.isOnMainThread()) {
                            RequestOptions myOptions = new RequestOptions()
                                    .error(R.drawable.iv_bg_video_right)
                                    .fitCenter()
                                    .optionalTransform
                                            (new GlideRoundedCorners(CommonUtils.dip2px(context, 5)
                                                    , GlideRoundedCorners.CornerType.ALL));
                            try {
                                Glide.with(VideoDetailContentActivity.this)
                                        .load(bannerInfo.getImgs().get(0))
                                        .apply(myOptions)
                                        .into(imageView);
                            } catch (Exception e) {
                            }

                        }
                    }
                }).start();

        footerlunbo.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Map<String, String> params = new HashMap<>();
                params.put("title", list.get(position).getTitle());
                params.put("articleId", id);
                params.put("advid", list.get(position).getId());
                params.put("adPosition", 2 + "");
                params.put("pageName","VideoDetailContentActivity");
                params.put("url2", list.get(position).getUrl2());
                params.put("carrierName", CommonUtils.getOperator(VideoDetailContentActivity.this));
                RouteUtils.RoutebyAd(getApplicationContext(), VideoDetailContentActivity.this, list.get(position).getUrl(), params);

//                RouteUtils.Route(VideoDetailContentActivity.this, list.get(position).getUrl(), list.get(position).getTitle());

            }
        });
    }

    /**
     * 取消收藏
     */
    public void getDeleteCollectActicles(String vid) {

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        headers.put("Authorization", SharepUtils.getString_info(VideoDetailContentActivity.this, SharepUtils.USER_LOGIN_TOKEN));
        String url = NetConfig.APPUSER__DELETE_COLLECTARTICLES
                + "/" + SharepUtils.getString_info(VideoDetailContentActivity.this, SharepUtils.USER_LOGIN_USERID)
                + "/collection/" + vid;

        OkHttpUtils.delete()
                .url(url)
                .headers(headers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {


                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();


                        GsonResultok packlist = gson.fromJson(response, GsonResultok.class);
                        int code = packlist.getCode();
                        if (code == 200) {
                            iv_video_sc.setImageResource(R.drawable.iv_video_sc);
                            is_sc = false;
                            SharepUtils.setString_info(VideoDetailContentActivity.this,"0", SharepUtils.IS_SC);
                            tv_video_sc.setText("收藏");
                        }
                    }
                });
    }
}
